//
//  LoginViewController.m
//  GoodWayClient
//
//  Created by HuiDong on 15/12/2.
//  Copyright © 2015年 HuiDong. All rights reserved.
//

#import "LoginViewController.h"
#import "AppDelegate.h"
#import "HomeViewController.h"
#import "AngelLeftMenuViewController.h"
#import "CarOwnerLeftMenuViewController.h"
#import "RegisterViewController.h"
#import "ResetPassWordViewController.h"

#import "Constant.h"
#import "AFNetworking.h"
#import "OwnerViewController.h"
#import "CarOwnerLeftMenuViewController.h"

#import "backGroundView.h"
@interface LoginViewController ()<UITextFieldDelegate,clearDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *logoImageView;
@property (weak, nonatomic) IBOutlet UIButton *oneBtn;

//重新设计登录框
@property (nonatomic,strong)UIView *background;

@property (nonatomic,strong)UITextField * account;
@property (nonatomic,strong)UITextField * psw;


//密码重置方法
- (IBAction)ResetPsd:(UIButton *)sender;
//记住密码状态改变方法
- (IBAction)RememberPsd:(id)sender;
//注册用户
- (IBAction)registerUser:(id)sender;


//额外添加
@property (nonatomic, assign) int a;

@end

@implementation LoginViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    //登录按钮
    UIButton *btn=[UIButton buttonWithType:UIButtonTypeSystem];
    btn.frame=CGRectMake(30, [UIScreen mainScreen].bounds.size.height/2+40, [UIScreen mainScreen].bounds.size.width-60, 50);
    [btn setBackgroundColor:[UIColor colorWithRed:51/255.0 green:102/255.0 blue:255/255.0 alpha:1]];
    btn.layer.cornerRadius=5.0;
    btn.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn setTitle:@"登录" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(btnEvent) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:btn];

#pragma newnew 1.7+の
    //设计账号密码框
    
    _background=[[backGroundView alloc]initWithFrame:CGRectMake(40, [UIScreen mainScreen].bounds.size.height/2-60, [UIScreen mainScreen].bounds.size.width-80, 80)];
    [_background setBackgroundColor:[UIColor whiteColor]];
    
    [[_background layer]setCornerRadius:5];
    [[_background layer] setMasksToBounds:YES];
    [self.view addSubview:_background];
    _account=[[UITextField alloc]initWithFrame:CGRectMake(40, _background.frame.origin.y, [UIScreen mainScreen].bounds.size.width-80, 40)];
    [_account setBackgroundColor:[UIColor clearColor]];
    UIImageView *imageView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"user"]];
    imageView.frame=CGRectMake(5, 0, 20, 20);
    _account.leftView= imageView;
    
    _account.leftViewMode=UITextFieldViewModeAlways;
    _account.placeholder=@"账号";
    _account.textAlignment=NSTextAlignmentLeft;
    _account.layer.cornerRadius=5.0;
    _account.clearButtonMode=UITextFieldViewModeAlways;
    _account.delegate=self;
    [self.view addSubview:_account];

    _psw=[[UITextField alloc]initWithFrame:CGRectMake(40, _account.frame.origin.y+40, [UIScreen mainScreen].bounds.size.width-80, 40)];
    _psw.placeholder=[NSString stringWithFormat:@"密码"];
    _psw.textAlignment=NSTextAlignmentLeft;
    _psw.layer.cornerRadius=5.0;
    [_psw setBackgroundColor:[UIColor clearColor]];
    
    _psw.clearButtonMode=UITextFieldViewModeAlways;//一次性清除
    _psw.secureTextEntry=YES;
    UIImageView * pswImage=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"password"]];
    
    
    _psw.leftView=pswImage;
    _psw.leftViewMode=UITextFieldViewModeAlways;
    _psw.delegate=self;
    [self.view addSubview:_psw];
    
    
    self.a = 0;
    
    
    //判断是否存在文件
    NSString *paths = NSHomeDirectory();
    
    //文件名
    NSString *uniquePath= [paths stringByAppendingString:@"/Library/Preferences/cn.brother.----.plist"];
    BOOL blHave=[[NSFileManager defaultManager] fileExistsAtPath:uniquePath];
    if (!blHave) {
        self.account.text = @"15515557023";
        self.psw.text = @"123456";
        self.a = 0;
        [self.oneBtn setBackgroundImage:[UIImage imageNamed:@"1.jpg"] forState:UIControlStateNormal];
        return ;
    }else {
        NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:uniquePath];
        self.account.text = dic[@"username"];
        self.psw.text = dic[@"password"];
        self.a = 1;
        [self.oneBtn setBackgroundImage:[UIImage imageNamed:@"2.jpg"] forState:UIControlStateNormal];
    }
}
-(void)btnEvent{
    
    NSLog(@"btnEvent");
    if (self.a == 1) {
        //记住密码
        //判断文件是否存在，不存在就创建
        //删除沙盒里面启动页版本的文件
        NSString *paths = NSHomeDirectory();
        
        //文件名
        NSString *uniquePath= [paths stringByAppendingString:@"/Library/Preferences/cn.brother.----.plist"];
        BOOL blHave=[[NSFileManager defaultManager] fileExistsAtPath:uniquePath];
        if (!blHave) {
            //创建
            NSDictionary *dic = @{@"username":self.account.text,@"password":self.psw.text};
            BOOL b = [dic writeToFile:uniquePath atomically:YES];
            if (b == 1) {
                [self loginRequest:self.account.text and:self.psw.text];
            }else
            {
                return;
            }
            return ;
        }else {
            [self loginRequest:self.account.text and:self.psw.text];
        }
    }else
    {
        //不记住密码
        //判断文件是否存在，存在就销毁
        //删除沙盒里面启动页版本的文件
        NSFileManager* fileManager=[NSFileManager defaultManager];
        NSString *paths = NSHomeDirectory();
        
        //文件名
        NSString *uniquePath= [paths stringByAppendingString:@"/Library/Preferences/cn.brother.----.plist"];
        BOOL blHave=[[NSFileManager defaultManager] fileExistsAtPath:uniquePath];
        if (!blHave) {
            [self loginRequest:self.account.text and:self.psw.text];
            return ;
        }else {
            BOOL blDele= [fileManager removeItemAtPath:uniquePath error:nil];
            if (blDele) {
                [self loginRequest:self.account.text and:self.psw.text];
            }else {
                return;
            }
        }
    }

    
}
//return键返回响应
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

//登录方法
- (IBAction)loginBtn:(UIButton *)sender {
    //设置登录按钮不可用
   // sender.enabled = NO;
    
    //设置提示warnView显示
//    [UIView beginAnimations:nil context:nil];
//    [UIView setAnimationBeginsFromCurrentState:YES];
//    [UIView setAnimationDuration:1.0f];
//    
//    self.warnView.hidden = YES;
//    [UIView commitAnimations];
    //self.warnView.hidden=YES;
    //判断是否记住密码
}


- (void)clear
{
    [self viewDidLoad];
}

- (void)loginRequest:(NSString *)username and: (NSString *)psd
{
    //网络请求
    AFHTTPRequestOperationManager *request = [AFHTTPRequestOperationManager manager];
    request.responseSerializer = [AFJSONResponseSerializer serializer];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"userName"] = self.account.text;
    dic[@"password"] = self.psw.text;
    
    [request POST:[NSString stringWithFormat:@"%@%@",url1,@"Login"] parameters:dic success:^(AFHTTPRequestOperation * operate, id responObj) {
        NSDictionary *dic = (NSDictionary *)responObj;
        if ([[NSString stringWithFormat:@"%@",dic[@"Status"]] isEqualToString:@"-1"]) {
            [[[UIAlertView alloc] initWithTitle:@"提示" message:@"用户名或密码错误！" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil] show];
        }else
        {
            NSDictionary *dic = (NSDictionary *)responObj;
            NSDictionary *data = dic[@"Data"];
            NSString *token = data[@"token"];
            NSString *role = data[@"role"];
            AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
            tempAppDelegate.token = token;//token为全app可用
            NSLog(@"TOKEN:%@",tempAppDelegate.token);
            if ([role isEqualToString:@"Company"]) {//区域公司
                
            }else if ([role isEqualToString:@"CType"]){//C类联盟商
                
            }else if ([role isEqualToString:@"InstallPoint"]){//安装点
                
            }else if ([role isEqualToString:@"User"]){//蓝天使者
                
                HomeViewController *mainVC = [self.storyboard instantiateViewControllerWithIdentifier:@"HomeViewController"];
                tempAppDelegate.mainNavigationController = [[UINavigationController alloc] initWithRootViewController:mainVC];
                AngelLeftMenuViewController *leftVC = [[AngelLeftMenuViewController alloc] init];
                tempAppDelegate.LeftSlideVC = [[LeftSlideViewController alloc] initWithLeftView:leftVC andMainView:tempAppDelegate.mainNavigationController];
                [self presentViewController:tempAppDelegate.LeftSlideVC animated:YES completion:nil];
            }else if([role isEqualToString:@"11"]){//车主用户
                
                OwnerViewController *mainVC = [self.storyboard instantiateViewControllerWithIdentifier:@"OwnerViewController"];
                tempAppDelegate.mainNavigationController = [[UINavigationController alloc] initWithRootViewController:mainVC];
                CarOwnerLeftMenuViewController *leftVC = [[CarOwnerLeftMenuViewController alloc] init];
               // leftVC.delegate = self;
                tempAppDelegate.LeftSlideVC = [[LeftSlideViewController alloc] initWithLeftView:leftVC andMainView:tempAppDelegate.mainNavigationController];
                [self presentViewController:tempAppDelegate.LeftSlideVC animated:YES completion:nil];
                
            }
        }
    } failure:^(AFHTTPRequestOperation * operate, NSError * error) {
        NSLog(@"%@",@"系统请求错误！");
        [[[UIAlertView alloc] initWithTitle:@"提示" message:@"系统请求有误!" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil] show];
    }];

}

//密码重置方法
- (IBAction)ResetPsd:(UIButton *)sender {
    UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    ResetPassWordViewController *vc = [mainStoryboard instantiateViewControllerWithIdentifier:@"ResetPassWordViewController"];
    [self presentViewController:vc animated:YES completion:nil];
}

//记住密码状态改变方法
- (IBAction)RememberPsd:(UIButton *)sender {
    if (self.a == 0) {
        [sender setBackgroundImage:[UIImage imageNamed:@"2.jpg"] forState:UIControlStateNormal];
        self.a = 1;
    }else
    {
        [sender setBackgroundImage:[UIImage imageNamed:@"1.jpg"] forState:UIControlStateNormal];
        self.a = 0;
    }
}

- (IBAction)registerUser:(id)sender {
    UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    RegisterViewController *vc = [mainStoryboard instantiateViewControllerWithIdentifier:@"RegisterViewController"];
    [self presentViewController:vc animated:YES completion:nil];
}
@end
